package com.timmy.chi.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.timmy.chi.MyApp;
import com.timmy.chi.R;
import com.timmy.chi.model.beans.Log;
import com.timmy.chi.ui.view.OneKeyDeleteEditView;
import com.timmy.chi.utils.SPUtils;
import com.timmy.chi.utils.StringUtil;
import com.timmy.chi.utils.network.MyHttp;
import com.timmy.chi.utils.network.ResultCallback;

import static com.timmy.chi.R.id.mobileInputView;
import static com.timmy.chi.R.id.passwordInputView;


/**
 * 登录页面
 */

public class LogInActivity extends AppCompatActivity implements View.OnClickListener {


    private OneKeyDeleteEditView mObileInputView;
    private OneKeyDeleteEditView mPasswordInputView;
    private Button nextStepBtn;
    private RadioGroup mGroup;
    private Gson mGson;
    private String userName;
    private String password;
    private Intent mIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initListener();
        initData();


        String uersname = (String) SPUtils.get(this, USER_NAME, "");
        String password = (String) SPUtils.get(this, USER_PASSWORD, "");

        if (!TextUtils.isEmpty(uersname) && !TextUtils.isEmpty(password)) {
            mObileInputView.setText(uersname);
            mPasswordInputView.setText(password);
        }

    }


    private void initView() {
        mObileInputView = (OneKeyDeleteEditView) findViewById(mobileInputView);
        mObileInputView.setMaxLength(11);
        mObileInputView.setInputType(InputType.TYPE_CLASS_PHONE);
        mObileInputView.setHint("请输入手机号码");


        mPasswordInputView = (OneKeyDeleteEditView) findViewById(passwordInputView);
        mPasswordInputView.setMaxLength(16);
        mPasswordInputView.setHint("请输入密码");
        mPasswordInputView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        nextStepBtn = (Button) findViewById(R.id.nextStepBtn);
        nextStepBtn.setEnabled(false);

        nextStepBtn.setOnClickListener(this);

        mGroup = (RadioGroup) this.findViewById(R.id.radioGroup);
        hideSoftKeyboard();
    }


    private void initListener() {
        mObileInputView.setInputViewActionListener(new OneKeyDeleteEditView.OnInputViewActionListener() {

            @Override
            public void onAction(int action) {
                if (OneKeyDeleteEditView.OnInputViewActionListener.ACTION_CLEAR_INPUT == action) {
                    mObileInputView.clearFocus();
                    mObileInputView.requestFocus();
                }
            }
        });

        mObileInputView.setTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                String currentContent = s.toString();
                if (!TextUtils.isEmpty(currentContent)) {
                    if (null != mPasswordInputView) {
                        String mobileContent = mPasswordInputView.getText();
                        if (!TextUtils.isEmpty(mobileContent)) {
                            if (null != nextStepBtn) {
                                nextStepBtn.setBackgroundResource(R.drawable.btn_red_selector);
                                nextStepBtn.setEnabled(true);
                                return;
                            }
                        }
                    }
                }
            }
        });


        mPasswordInputView.setInputViewActionListener(new OneKeyDeleteEditView.OnInputViewActionListener() {
            @Override
            public void onAction(int action) {
                if (OneKeyDeleteEditView.OnInputViewActionListener.ACTION_CLEAR_INPUT == action) {
                    mPasswordInputView.clearFocus();
                    mPasswordInputView.requestFocus();
                }
            }
        });

        mPasswordInputView.setTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String currentContent = s.toString();
                if (!TextUtils.isEmpty(currentContent)) {
                    if (null != mObileInputView) {
                        String mobileContent = mObileInputView.getText();
                        if (!TextUtils.isEmpty(mobileContent)) {
                            if (null != nextStepBtn) {
                                nextStepBtn.setBackgroundResource(R.drawable.btn_red_selector);
                                nextStepBtn.setEnabled(true);
                                return;
                            }
                        }
                    }
                }
                nextStepBtn.setBackgroundResource(R.drawable.btn_normal_bg);
                nextStepBtn.setEnabled(false);
            }
        });
    }

    private void initData() {

        mGson = new Gson();
    }

    /**
     * 关闭软键盘
     */
    public void hideSoftKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 关闭软键盘
     */
    public void hideSoftKeyboard(View view) {
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 显示软键盘
     */
    public void showSoftKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.nextStepBtn:
                userName = mObileInputView.getText().toString();
                password = mPasswordInputView.getText().toString();
                if (!StringUtil.isValidatePhoneNumber(userName)) {
                    mObileInputView.setError("请输入正确的手机号码");
                    return;
                } else if (!StringUtil.isValidatePasswordByLogin(password)) {
                    mPasswordInputView.setError(getString(R.string.passwordRule));
                    return;
                }

                nextStepBtn.setEnabled(false);
                hideSoftKeyboard();

                submit();

                break;
        }
    }

    private String USER_NAME = "username";
    private String USER_PASSWORD = "password";

    private void submit() {
        nextStepBtn.setEnabled(true);

        int checkId = mGroup.getCheckedRadioButtonId();
        mIntent = null;

        switch (checkId) {
            case R.id.rb_guke:
                mIntent = new Intent(this, MainActivity.class);
                break;
            case R.id.rb_chushi:


                if (!userName.equals("17688563232")) {
                    if (!userName.equals("18301912592")) {
                        Toast.makeText(LogInActivity.this, "厨师账号密码错误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                mIntent = new Intent(this, HouTaiActivity.class);
                break;
            case R.id.rb_admin:

                if (!userName.equals("17688563232")) {
                    if (!userName.equals("18301912592")) {
                        Toast.makeText(LogInActivity.this, "管理员账号密码错误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                mIntent = new Intent(this, AdminActivity.class);
                break;
        }

        login();

    }

    public void login() {

        MyHttp.login(userName, password, new ResultCallback() {
            @Override
            public void onSuccess(String s) {

                Log log = mGson.fromJson(s, Log.class);

                if (log.getResponseState() == 0) {
                    SPUtils.put(LogInActivity.this, USER_NAME, userName);
                    SPUtils.put(LogInActivity.this, USER_PASSWORD, password);

                    // 保存到内存中

                    MyApp.uId = log.getUid();
                    Toast.makeText(LogInActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                    startActivity(mIntent);
                    finish();
                } else {
                    Toast.makeText(LogInActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError() {
                Toast.makeText(LogInActivity.this, "请检查服务器", Toast.LENGTH_SHORT).show();
            }
        });
    }
}